<?php

/**
 * Subclass for representing a row from the 'seo' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Seo extends BaseSeo
{
	public static function toSeo($objType, $objAction, $objId, $name, $url, $unique = true) 
	{
	    if( $objType && $objAction && $objId && $name) 
	    {	
	        $c = new Criteria();
			$c->add(SeoPeer::OBJ_TYPE, $objType);
			$c->add(SeoPeer::OBJ_ACTION, $objAction);
			$c->add(SeoPeer::OBJ_ID, $objId);
			$seo = SeoPeer::doSelectOne($c);
			if( !$seo ) 
			{ 
			    $newSeo = new Seo();
				if( $url ) 
				{
				    $newSeo->setUrl($url);
				}
				else 
				{
				    $newSeo->setUrl(Seo::slugify($name));
				}
				$newSeo->setObjType($objType);
				$newSeo->setObjAction($objAction);
				$newSeo->setObjId($objId);
				$newSeo->save();
			}
			else 
			{
				if( $url ) 
				{
				    $seo->setUrl($url);
					$seo->save();
				}
				else 
				{
				    $seo->setUrl(Seo::slugify($name));
					$seo->save();
				}
			}
	    }
	}

	public static function slugify($text) 
	{
	    if( $text ) 
	    {
			// replace non letter or digits by -
			$text = preg_replace('~[^\\pL\d]+~u', '-', $text);

			// trim
			$text = trim($text, '-');

			$text = str_replace(array('ą', 'č', 'ę', 'ė', 'į', 'š', 'ų', 'ū', 'ž', 'Ą', 'Č', 'Ę', 'Ė', 'Į', 'Š', 'Ų', 'Ū', 'Ž'), array('a', 'c', 'e', 'e', 'i', 's', 'u', 'u', 'z', 'A', 'C', 'E', 'E', 'I', 'S', 'U', 'U', 'Z'), $text);

			// transliterate
			$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

			// lowercase
			$text = strtolower($text);

			// remove unwanted characters
			$text = preg_replace('~[^-\w]+~', '', $text);

			return $text;
	    }
		else 
		{
		    return '#';
		}
	}
}
